<template>
  <view class="container">
    <!-- 顶部图片 -->
    <view style="background-image: url(../../../static/tabBar/top.png);width: 100%;height: 300rpx;"></view>

    <!-- 查询交费 -->
    <view class="center-container">
      <view class="rounded-box plate-number-input">
        <text>请输入车牌号</text>
        
        <!-- 车牌号输入框 -->
        <view class="inputs custom-input-class">
          <view :class="'inputs-item custom-item-class ' + (currentInput === 0 ? 'item-active' : '')" @tap="showProvinceBoard">{{ plateNumber[0] }}</view>
          <view :class="'inputs-item custom-item-class ' + (currentInput === 1 ? 'item-active' : '')" @tap="showAreaBoard">{{ plateNumber[1] }}</view>
          <view class="split">·</view>
          <view :class="'inputs-item custom-item-class ' + (currentInput === 2 ? 'item-active' : '')" @tap="showNumberBoard" :data-index="2">{{ plateNumber[2] }}</view>
          <view :class="'inputs-item custom-item-class ' + (currentInput === 3 ? 'item-active' : '')" @tap="showNumberBoard" :data-index="3">{{ plateNumber[3] }}</view>
          <view :class="'inputs-item custom-item-class ' + (currentInput === 4 ? 'item-active' : '')" @tap="showNumberBoard" :data-index="4">{{ plateNumber[4] }}</view>
          <view :class="'inputs-item custom-item-class ' + (currentInput === 5 ? 'item-active' : '')" @tap="showNumberBoard" :data-index="5">{{ plateNumber[5] }}</view>
          <view :class="'inputs-item custom-item-class ' + (currentInput === 6 ? 'item-active' : '')" @tap="showNumberBoard" :data-index="6">{{ plateNumber[6] }}</view>
          <view :class="'inputs-item custom-item-class ' + (currentInput === 7 ? 'item-active' : '')" @tap="showNumberBoard" :data-index="7">
            <text class="new" v-if="!plateNumber[7] && !isNewEnergy">+</text>
            <text v-else>{{ plateNumber[7] }}</text>
          </view>
        </view>
        
        <!-- 查询并交费按钮 - 始终保持激活状态 -->
        <button class="query-pay-button" @click="queryAndPay">查询并交费</button>
      </view>
    </view>

    <!-- 温馨提示 -->
    <view class="warm-tip">
      <text>温馨提示：请缴费后15分钟内离场，否则系统将重新计费</text>
    </view>

    <!-- 功能图标区 -->
    <view class="rounded-box function-icons">
      <view class="icon-item" @click="viewPaymentRecords">
        <image class="icon" src="../../../static/tabBar/jfjl.png"></image>
        <text>缴费记录</text>
      </view>
      <view class="icon-item" @click="manageVehicles">
        <image class="icon" src="../../../static/tabBar/clgl.png"></image>
        <text>车辆管理</text>
      </view>
      <view class="icon-item" @click="issueInvoice">
        <image class="icon" src="../../../static/tabBar/kjfp.png"></image>
        <text>开具发票</text>
      </view>
      <view class="icon-item" @click="enableAutoPay">
        <image class="icon" src="../../../static/tabBar/mmzf.png"></image>
        <text>免密支付</text>
      </view>
      <view class="icon-item" @click="contactCustomerService">
        <image class="icon" src="../../../static/tabBar/lxkf.png"></image>
        <text>联系客服</text>
      </view>
    </view>

    <!-- 会员停车权益说明 - 添加点击事件 -->
    <view class="rounded-box member-rights" @click="showRightsPanel">
      <text>会员停车权益说明</text>
    </view>
    
    <!-- 会员权益面板 - 默认隐藏 -->
    <view class="rights-panel" :class="{ 'show-panel': rightsPanelVisible }">
      <view class="panel-header">
        <text class="panel-title">会员停车权益说明</text>
        <view class="close-btn" @click="hideRightsPanel">×</view>
      </view>
      <view class="panel-content" v-html="formatLineBreaks(memberRights)"></view>
    </view>

    <!-- 虚拟键盘 -->
    <view class="keyboard" v-if="keyboardVisible">
      <view class="keyboardClose">
        <view class="keyboardClose_btn" @tap="closeKeyboard">关闭</view>
      </view>
      
      <!-- 省份简写键盘 -->
      <view class="keyboard-item" v-if="keyboardType === 1">
        <view class="keyboard-line" v-for="(item, index) in provinces" :key="index">
          <view class="keyboard-btn" :data-val="itemlist" @tap="chooseProvince" v-for="(itemlist, index1) in item" :key="index1">
            {{ itemlist }}
          </view>
        </view>
        <view class="keyboard-del" @tap="delProvince">
          <text>清除</text>
        </view>
      </view>
      
      <!-- 地区简写键盘 -->
      <view class="keyboard-item" v-if="keyboardType === 2">
        <view class="keyboard-line" v-for="(item, index) in areas" :key="index">
          <view class="keyboard-btn" :data-val="itemlist" @tap="chooseArea" v-for="(itemlist, index1) in item" :key="index1">
            {{ itemlist }}
          </view>
        </view>
        <view class="keyboard-del" @tap="delArea">
          <text>清除</text>
        </view>
      </view>
      
      <!-- 普通类型键盘 -->
      <view class="keyboard-item" v-if="keyboardType === 3">
        <view class="keyboard-line" v-for="(item, index) in numbers" :key="index">
          <view class="keyboard-btn" :data-val="itemlist" @tap="chooseNumber" v-for="(itemlist, index1) in item" :key="index1">
            {{ itemlist }}
          </view>
        </view>
        <view class="keyboard-del" @tap="delNumber">
          <text>清除</text>
        </view>
      </view>
      
      <!-- 最后一位键盘 -->
      <view class="keyboard-item" v-if="keyboardType === 4">
        <view class="keyboard-line" v-for="(item, index) in last" :key="index">
          <view class="keyboard-btn" :data-val="itemlist" @tap="chooseLast" v-for="(itemlist, index1) in item" :key="index1">
            {{ itemlist }}
          </view>
        </view>
        <view class="keyboard-del" @tap="delLast">
          <text>清除</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import {getMemberCarByPhone, getCarOrderOfJS, getParkConfigList} from '@/api/parking.js';
import { getPhoneApi } from '@/api/user';
export default {
  data() {
    return {
      memberRights: '', // 会员权益说明
      plateNumber: Array(8).fill(''),
      currentInput: 0, // 从0开始输入
      keyboardVisible: false,
      keyboardType: 1, // 默认显示省份键盘
      isNewEnergy: false,
      memberCar: false,
      attributes: {}, // 存储订单属性
      rightsPanelVisible: false, // 会员权益面板显示状态
      // 省份输入
      provinces: [
        ['京', '沪', '粤', '津', '冀', '晋', '蒙', '辽', '吉', '黑'],
        ['苏', '浙', '皖', '闽', '赣', '鲁', '豫', '鄂', '湘'],
        ['桂', '琼', '渝', '川', '贵', '云', '藏'],
        ['陕', '甘', '青', '宁', '新']
      ],
      // 地区输入
      areas: [
        ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K'],
        ['L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V'],
        ['W', 'X', 'Y', 'Z']
      ],
      // 车牌输入
      numbers: [
        ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],
        ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K'],
        ['L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V'],
        ['W', 'X', 'Y', 'Z']
      ],
      // 最后一位输入
      last: [
        ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],
        ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K'],
        ['L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V'],
        ['W', 'X','Y', 'Z','港', '澳', '学', '挂', '警']
      ]
    };
  },
  created() {
    this.plateNumber[0] = '苏';
  },
  computed: {
    // 按钮不再需要禁用状态
    btnDisabled() {
      return false;
    }
  },
  onLoad() {
    let params = {
      parkId: "p240199697"
    }
    getParkConfigList(params).then(res => {
      console.log('获取规则:', res);
      if (res.total > 0) {
        this.memberRights = res.rows[0].memberRights;
      }
    })
    .catch(err => {
      console.error('获取规则失败:', err);
    });
  },
  methods: {

      // 转换换行符为<br>标签
    formatLineBreaks(text) {
      if (!text) return '';
      // 将\n转换为<br>，同时处理连续换行
      return text.replace(/\n/g, '<br>');
    },

    // 显示会员权益面板
    showRightsPanel() {
      this.rightsPanelVisible = true;
      // 滚动到顶部，确保面板显示正常
      uni.pageScrollTo({
        scrollTop: 0,
        duration: 300
      });
    },
    
    // 隐藏会员权益面板
    hideRightsPanel() {
      this.rightsPanelVisible = false;
    },
    
    closeKeyboard() {
      this.keyboardVisible = false;
    },

    /**
     * 显示省份键盘
     */
    showProvinceBoard() {
      this.keyboardVisible = true;
      this.currentInput = 0;
      this.keyboardType = 1;
    },

    /**
     * 选定省份
     */
    chooseProvince(event) {
      const { val } = event.currentTarget.dataset;
      this.$set(this.plateNumber, 0, val);
      this.currentInput = 1;
      this.keyboardType = 2;
    },

    /**
     * 删除选定省份
     */
    delProvince() {
      this.$set(this.plateNumber, 0, '');
      this.currentInput = 0;
      this.keyboardType = 1;
    },

    /**
     * 显示地区键盘
     */
    showAreaBoard() {
      this.keyboardVisible = true;
      this.currentInput = 1;
      this.keyboardType = 2;
    },

    /**
     * 选定地区
     */
    chooseArea(event) {
      const { val } = event.currentTarget.dataset;
      this.$set(this.plateNumber, 1, val);
      this.currentInput = 2;
      this.keyboardType = 3;
    },

    /**
     * 删除选定区域
     */
    delArea() {
      this.$set(this.plateNumber, 1, '');
      this.currentInput = 1;
      this.keyboardType = 2;
    },

    /**
     * 显示普通键盘
     */
    showNumberBoard(event) {
      const { index } = event.currentTarget.dataset;
      const keyboardType = index === 6 || index === 7 ? 4 : 3;
      this.keyboardVisible = true;
      this.currentInput = index;
      this.keyboardType = keyboardType;
      
      // 处理新能源车牌
      if (index === 7 && !this.isNewEnergy && !this.plateNumber[7]) {
        this.isNewEnergy = true;
      }
    },

    /**
     * 选定车牌
     */
    chooseNumber(event) {
      const { val } = event.currentTarget.dataset;
      this.$set(this.plateNumber, this.currentInput, val);
      
      // 跳到最后一位时，键盘不一样
      if (this.currentInput === 6 && !this.isNewEnergy) {
        this.keyboardType = 4;
      } else if (this.currentInput === 7 && this.isNewEnergy) {
        this.keyboardType = 4;
      }
      
      // 移动到下一个输入框
      if (this.currentInput < 7) {
        this.currentInput++;
      } else {
        // 已经是最后一个输入框，关闭键盘
        this.keyboardVisible = false;
      }
    },

    /**
     * 删除车牌
     */
    delNumber() {
      this.$set(this.plateNumber, this.currentInput, '');
      
      // 如果删除到地区时，切换键盘类型
      if (this.currentInput === 1) {
        this.keyboardType = 2;
      } else if (this.currentInput > 1) {
        this.keyboardType = 3;
      }
      
      // 移动到上一个输入框
      if (this.currentInput > 0) {
        this.currentInput--;
      }
    },

    /**
     * 选定最后一位
     */
    chooseLast(event) {
      const { val } = event.currentTarget.dataset;
      this.$set(this.plateNumber, this.currentInput, val);
      
      // 移动到下一个输入框或关闭键盘
      if (this.currentInput < 7) {
        this.currentInput++;
      } else {
        this.keyboardVisible = false;
      }
    },

    /**
     * 删除最后一位
     */
    delLast() {
      this.$set(this.plateNumber, this.currentInput, '');
      
      // 移动到上一个输入框
      if (this.currentInput > 0) {
        this.currentInput--;
      }
      
      // 调整键盘类型
      if (this.currentInput < 6) {
        this.keyboardType = 3;
      } else {
        this.keyboardType = 4;
      }
    },

    memberExsist(param) {
      return new Promise((resolve, reject) => {
        getMemberCarByPhone({ licensePlate: param })
          .then(res => {
            this.memberCar = res.total > 0;
            resolve(this.memberCar);
          })
          .catch(err => {
            console.error('查询会员车辆失败', err.msg);
            reject(err);
          });
      });
    },

    // 新增：获取订单信息的方法
    getOrderInfo(carNum) {
      return new Promise((resolve, reject) => {
        getCarOrderOfJS({ carNo: carNum })
          .then(res => {
            if (res.code === 200 && res.data.length > 0) {
              this.attributes = res.data[0].attributes;
              resolve(this.attributes);
            } else {
              uni.showToast({ title: '未查询到订单信息', icon: 'none' });
              reject(new Error('未查询到订单信息'));
            }
          })
          .catch(err => {
            console.error('查询订单失败', err);
            uni.showToast({ title: '查询订单失败，请重试', icon: 'none' });
            reject(err);
          });
      });
    },
    
    // 验证车牌号格式
    validatePlateNumber(plateNumber) {
      // 检查省份简称
      if (!plateNumber[0]) {
        return false;
      }
      
      // 检查地区代码
      if (!plateNumber[1]) {
        return false;
      }
      
      // 检查至少有一个数字或字母
      for (let i = 2; i < 7; i++) {
        if (plateNumber[i]) {
          return true;
        }
      }
      
      return false;
    },
    
    queryAndPay() {

     //点击缴费前，先判断是否登录
      const openid = uni.getStorageSync('openid');
      console.log('打印 openid',openid);
      if(openid == null || openid == '' ||  openid == undefined || openid == 'undefined'){
        // 跳转到登录页面
        // uni.navigateTo({
        //   url: '/pages/users/wechat_login/index'
        // });


        uni.showModal({
          title: '提示',
          content: '您尚未登录不能使用该功能，是否前往登录页面？',
          success: (res) => {
            if (res.confirm) {
              // 用户点击确定，跳转到登录页
              uni.navigateTo({
                url: '/pages/users/wechat_login/index'
              });
            } else if (res.cancel) {
              // 用户点击取消，可做其他处理（比如返回首页）
              console.log('用户取消了登录操作');
            }
          }
        });
        return;



      }else{


      // 验证车牌号
      if (!this.validatePlateNumber(this.plateNumber)) {
        uni.showToast({ title: '请输入正确的车牌号', icon: 'none' });
        return;
      }

      const carNum = this.plateNumber[0] + '-' + this.plateNumber.slice(1).join('').replace(/\s/g, '');

      console.log('车牌号:', carNum);
      
      // uni.showLoading({ title: '查询中...' });
      
      // 先查询会员车辆信息
      this.memberExsist(carNum)
        .then(isMember => {
          // 再查询订单信息
          return this.getOrderInfo(carNum);
        })
        .then(attributes => {
          uni.hideLoading();
          console.log('订单信息：', attributes);
          if(attributes.retcode == "2"){
            uni.showModal({ title: '未查询到该车辆的入场信息' });

          }else{
          
            // 跳转至收银台页面并传递参数
            uni.navigateTo({
              url: `/pages/parking/checkstand_pay/index?carNum=${encodeURIComponent(carNum)}&memberCar=${this.memberCar}&attributes=${encodeURIComponent(JSON.stringify(attributes))}`
            });
          }
        })
        .catch(err => {
          uni.hideLoading();
          console.error('查询流程异常', err);
          if(err.msg !='未登录'){
             uni.showToast({
            title: '没有找到入场记录',
            icon: 'none',
            duration: 2000
          });
          }
         
        });
        }
    },
    
    viewPaymentRecords() {
      uni.navigateTo({ url: '/pages/parking/payment_records/index' });
    },

    async manageVehicles() {
      const phone = uni.getStorageSync('phone');
      getPhoneApi

      if (!phone) {
        const shouldLogin = await this.showLoginConfirmModal();
        if (shouldLogin) {
          uni.navigateTo({
            url: '/pages/users/wechat_login/index'
          });
        }
        return;
      }

      uni.navigateTo({ url: '/pages/parking/car_manage/index' });
    },


    
    issueInvoice() {
      uni.navigateTo({ url: '/pages/parking/issue_invoice/index' });
    },
    
    enableAutoPay() {
      uni.navigateTo({ url: '/pages/parking/issue_invoice/index' });
    },
    
    contactCustomerService() {
      uni.showModal({
        title: '联系客服',
        content: '您可以选择拨打电话或跳转客服页面进行咨询',
        confirmText: '拨打电话',
        cancelText: '跳转客服页面',
        success: (res) => {
          if (res.confirm) console.log('模拟拨打电话');
          else uni.navigateTo({ url: '/pages/customerService' });
        }
      });
    },




    // getPhoneApi(){      
    //     // 获取不加密手机号
    //     getPhoneApi().then(res => {
    //       console.log('获取不加密手机号：',res);
    //       uni.setStorageSync('phone', res.data.phone);

    //     }).catch(res => {
    //       console.log('的getUserInfo错误=',res);
    //       if(res.msg == '未登录'){
            
    //         // 跳转到登录页面
    //         // uni.navigateTo({
    //         //   url: '/pages/users/wechat_login/index'
    //         // });


    //         uni.showModal({
    //           title: '提示',
    //           content: '您尚未登录不能使用该功能，是否前往登录页面？',
    //           success: (res) => {
    //             if (res.confirm) {
    //               // 用户点击确定，跳转到登录页
    //               uni.navigateTo({
    //                 url: '/pages/users/wechat_login/index'
    //               });
    //             } else if (res.cancel) {
    //               // 用户点击取消，可做其他处理（比如返回首页）
    //               console.log('用户取消了登录操作');
    //             }
    //           }
    //         });
    //       }
    //     });
						
    // },


async getPhoneApi() {
  try {
    const res = await getPhoneApi();
    console.log('获取不加密手机号：', res);
    uni.setStorageSync('phone', res.data.phone);
  } catch (err) {
    console.log('的getUserInfo错误=', err);

    if (err.msg === '未登录') {
      const shouldLogin = await this.showLoginConfirmModal(); // 等待用户选择
      if (shouldLogin) {
        uni.navigateTo({
          url: '/pages/users/wechat_login/index'
        });
      }
    }
  }
},






    // 封装一个统一的确认对话框
    async showLoginConfirmModal() {
      return new Promise((resolve, reject) => {
        uni.showModal({
          title: '提示',
          content: '您尚未登录，是否前往登录页面？',
          success: (res) => {
            if (res.confirm) {
              resolve(true);
            } else if (res.cancel) {
              resolve(false);
            }
          },
          fail: () => {
            resolve(false);
          }
        });
      });
    }

  }
};
</script>

<style scoped lang="scss">
.container {
  position: relative;
  z-index: 1;
}

.center-container {
  width: 95%;
  margin: 0 auto;
  padding: 20rpx 0;
}

.top-image {
  width: 100%;
  height: 300rpx;
  display: block;
}

.cart_nav {
  position: fixed;
  @include main_bg_color(theme);
  top: 0;
  left: 0;
  z-index: 99;
  width: 100%;
}

.rounded-box {
  background-color: rgba(255, 255, 255, 1.00);
  border-radius: 16rpx;
  padding: 20rpx;
  margin-bottom: 30rpx;
}

.member-rights{
  float: right;
  background-color: transparent !important;
}

.inputs {
  display: flex;
  align-items: center;
  width: 100%;
  margin: 150rpx auto 80rpx auto;
  justify-content: center;
}

.split {
  font-weight: bold;
  font-size: 48rpx;
  margin: 0 10rpx;
}

.inputs-item {
  border: 1rpx solid #8d8d8d;
  border-radius: 12rpx;
  margin: 10rpx;
  width: 68rpx;
  font-size: 48rpx;
  text-align: center;
  height: 86rpx;
  line-height: 86rpx;
}

.item-active {
  border: 2rpx solid #ff6e00;
  color: #ff6e00;
}

.keyboard {
  position: fixed;
  bottom: 0;
  background-color: #d1d5d9;
  width: 100%;
  left: 0;
  padding: 10rpx 0;
  z-index: 1000;
  box-sizing: border-box;
}

.keyboardClose {
  height: 70rpx;
  background-color: #f7f7f7;
  overflow: hidden;
  padding: 0 20rpx;
}

.keyboardClose_btn {
  float: right;
  line-height: 70rpx;
  font-size: 15px;
}

.keyboard-line {
  display: flex;
  justify-content: center;
  flex-wrap: nowrap;
  padding: 5rpx 10rpx;
  box-sizing: border-box;
  margin: 0 auto;
  width: 99%;
}

.keyboard-btn {
  font-size: 32rpx;
  color: #333333;
  background: #fff;
  text-align: center;
  box-shadow: 0 2rpx 0 0 #999999;
  border-radius: 10rpx;
  margin: 5rpx;
  width: 60rpx;
  height: 60rpx;
  line-height: 60rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  flex: 1 0 60rpx;
  max-width: 60rpx;
}

.keyboard-del {
  font-size: 32rpx;
  color: #333333;
  background: #a7b0bc;
  display: inline-block;
  padding: 0;
  box-shadow: 0 2rpx 0 0 #999999;
  border-radius: 10rpx;
  margin: 5rpx;
  width: 120rpx;
  height: 60rpx;
  line-height: 60rpx;
  text-align: center;
  position: absolute;
  bottom: 15rpx;
  right: 15rpx;
}

.plate-number-suggest {
  display: flex;
  flex-wrap: wrap;
  margin-top: 10rpx;
}

.plate-number-suggest text {
  margin-right: 10rpx;
  background-color: #f5f5f5;
  padding: 5rpx 10rpx;
  border-radius: 5rpx;
}

/* 查询并交费按钮 - 保持原有样式 */
.query-pay-button {
  width: 85%;
  height: 90rpx;
  background-color: #ff6666;
  color: white;
  border: none;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 38rpx;
  margin: 20rpx auto;
  opacity: 1; /* 保持按钮始终激活 */
  cursor: pointer;
}

.warm-tip {
  margin-top: 40rpx;
  margin-bottom: 40rpx;
  color: #ff3333;
  padding: 20rpx;
  background-color: #fffbe6;
  border-radius: 16rpx;
}

.function-icons {
  display: flex;
  justify-content: space-around;
}

.icon-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.icon {
  width: 50rpx;
  height: 50rpx;
}

.new {
  color: #999;
  text-align: center;
  font-size: 36rpx;
  width: 100%;
  vertical-align: top;
}

/* 会员权益面板样式 */
.rights-panel {
  position: fixed;
  bottom: -100%;
  left: 0;
  width: 100%;
  max-height: 80vh;
  background-color: #fff;
  border-radius: 20rpx 20rpx 0 0;
  z-index: 999;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.1);
  transition: bottom 0.3s ease;
  overflow: hidden;
}

.rights-panel.show-panel {
  bottom: 0;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 40rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.panel-title {
  font-size: 36rpx;
  font-weight: bold;
  margin:0 auto;
}

.close-btn {
  font-size: 48rpx;
  color: #999;
  padding: 10rpx;
}

.panel-content {
  padding: 30rpx;
  font-size: 28rpx;
  line-height: 1.6;
  overflow-y: auto;
  max-height: calc(80vh - 120rpx);
}
</style>